/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.brucexx.wedding.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import sun.util.logging.resources.logging;

import com.brucexx.wedding.dao.BaseModelDAO;
import com.brucexx.wedding.model.PicInfo;
import com.brucexx.wedding.util.BeanHelper;
import com.brucexx.wedding.util.DateHelper;
import com.brucexx.wedding.util.StringHelper;

/**
 * 
 * @author BruceXX email:brucest0078@gmail.com
 * 
 */
@Controller
public class WallController {

	private static final Log logger = LogFactory.getLog(WallController.class);

	@RequestMapping(value = "/picwall.action", method = RequestMethod.GET)
	public String gotoPicWall(HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		String action = StringHelper
				.null2String(request.getParameter("action"));
		String flag = StringHelper.null2String(request.getParameter("flag"));
		if (action.equals("loadpic")) {
			response.setContentType("text/json");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Cache-Control", "no-cache");

			String gql = "select  from " + PicInfo.class.getName()
					+ " where flag=='" + flag + "' order by yearMonth desc";
			List<PicInfo> list = BaseModelDAO.executeSqlForList(gql);
			Map<String, List<PicInfo>> map = new LinkedHashMap<String, List<PicInfo>>();

			for (PicInfo picInfo : list) {
				String key = picInfo.getYearMonth();
				if (map.get(key) == null) {
					map.put(key, new ArrayList<PicInfo>());
				}
				map.get(key).add(picInfo);
			}
			JSONArray jsonResult = new JSONArray();
			for (Map.Entry<String, List<PicInfo>> entry : map.entrySet()) {
				JSONObject wrapObj = new JSONObject();
				JSONArray jsonList = new JSONArray();
				for (PicInfo picInfo : entry.getValue()) {
					JSONObject tmp = new JSONObject();
					BeanHelper.copyProperties2JSON(tmp, picInfo, "gmtCreate");
					tmp.put("gmtCreate",
							DateHelper.getChinaDateTime(picInfo.getGmtCreate()));
					jsonList.add(tmp);
				}
				wrapObj.put("key", entry.getKey());
				wrapObj.put("value", entry.getValue());
				jsonResult.add(wrapObj);
			}
			response.getWriter().write(jsonResult.toString());
			return null;
		}

		return "pic/pic_wall";
	}

}
